package priv.lhy.activity.intercept;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import priv.lhy.activity.controller.BaseController;
import priv.lhy.annotation.Anoymous;
import priv.lhy.constans.WebConstant;
import priv.lhy.dto.CheckAuthRequest;
import priv.lhy.dto.CheckAuthResponse;
import priv.lhy.user.IUserCoreService;
import priv.lhy.utils.CookieUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * author : lihy
 * date : 2019/2/21 9:23
 */
public class TokenIntercepter extends HandlerInterceptorAdapter {

    private static final String ACCESS_TOEKN = "access_token";

    @Autowired
    IUserCoreService userCoreService;

    /***
     * token验证
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //非spring管理类不拦截
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Object bean = handlerMethod.getBean();

        //未继承baseController的抛出
        if (!(bean instanceof BaseController)) {
            throw new RuntimeException("must extend baseController");
        }

        String token = CookieUtils.getCookieValue(request, ACCESS_TOEKN);
        boolean isAjax = CookieUtils.isAjax(request);
        //无token信息
        if (StringUtils.isEmpty(token)) {
            //ajax请求者返回json错误信息
            if (isAjax) {
                response.setContentType("text/html;charset=UTF-8");
                response.getWriter().write("{\"code\":\"-1\", \"msg\":\"error\", \"url\":\"" + WebConstant.SSO_ACCESS_URL + "\"}");
                return false;
            }
            //正常请求直接跳转
            response.sendRedirect(WebConstant.SSO_ACCESS_URL);
            return false;
        }
        CheckAuthRequest checkAuthRequest = new CheckAuthRequest();
        checkAuthRequest.setToken(token);
        CheckAuthResponse checkAuthResponse = userCoreService.validToken(checkAuthRequest);
        if ("000000".equals(checkAuthResponse.getCode())) {
            BaseController baseController = (BaseController) bean;
            baseController.setUid(checkAuthResponse.getUid());
            return super.preHandle(request, response, handler);
        }
        if (isAjax) {
            response.setContentType("text/html;charset=UTF-8");
            response.getWriter().write("{\"code\":\"" + checkAuthResponse.getCode() + "\", \"msg\":\"" + checkAuthResponse.getMsg() + "\", \"url\":\"" + WebConstant.SSO_ACCESS_URL + "\"}");
            return false;
        }
        response.sendRedirect(WebConstant.SSO_ACCESS_URL);
        return false;
    }

    /**
     * 是否允许匿名访问
     *
     * @param handlerMethod
     * @return
     */
    private boolean isAnoymous(HandlerMethod handlerMethod) {
        Object bean = handlerMethod.getBean();
        Class clazz = bean.getClass();
        //注解在类上
        if (clazz.getAnnotation(Anoymous.class) != null) {
            return true;
        }
        //注解在方法上
        Method method = handlerMethod.getMethod();
        return method.getAnnotation(Anoymous.class) != null;
    }
}
